<?php
/**
 * @desc: 发送邮件方法
 * @Author: delayhsiao
 * @update: 2016-11-15
 **/
function send_mail($email, $subject, $html) {
	$mail = new \PHPMailer();
	$mail->isSMTP();
	$mail->SMTPDebug = 0;
	$mail->Debugoutput = 'html';
	$mail->Host = "smtp.exmail.qq.com";
	$mail->Port = 25;
	$mail->SMTPAuth = true;
	$mail->Username = "order@baimixu.com";
	$mail->Password = "BMX1256bmx";
	$mail->setFrom('order@baimixu.com', '享买');
	$mail->addReplyTo('order@baimixu.com', '享买');
	$mail->addAddress($email, $email);
	$mail->Subject = $subject;
	$mail->msgHTML($html);
	$mail->AltBody = '这是一封HTML邮件，请使用网页版邮箱查看';
	if (!$mail->send()) {
		return false;
	} else {
		return true;
	}
}

/**
 * @desc:  随机生成6位数字
 * @Author: cheng
 **/
function GetRandStr($len) {
    $chars = array(
//        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
//        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
//        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
//        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
//        "S", "T", "U", "V", "W", "X", "Y", "Z",
        "0", "1", "2","3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i=0; $i<$len; $i++)
    {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

/**
 * @desc: 短信发送方法
 * @Author: delayhsiao
 * @update: 2016-11-15
 **/
function send_sms($mobile,$content,$spareNum=0){
    if($spareNum==0){       
        //$smsUrl = "http://114.55.25.138/msg/HttpBatchSendSM?account=xmksyzm&pswd=Xmks2016@&mobile={mobile}&msg={content}&needstatus=true&product=&extno=";
        $smsUrl = "http://114.55.25.138/msg/HttpBatchSendSM?account=".C('SMS_ACCOUNT')."&pswd=".C('SMS_SECRET')."&mobile={mobile}&msg={content}&needstatus=true&product=&extno=";
        $smsUrl = str_replace("{mobile}",$mobile,$smsUrl);
        $content = urlencode($content);   //短信内容转码
        $smsUrl = str_replace("{content}", $content,$smsUrl);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $smsUrl);        //设置url
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);   //设置开启重定向支持
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        $output = curl_exec($ch);  //执行
        curl_close($ch);
        return $output;
    }else{
        // 启用备用多接口发送  根据 $spareNum 来决定哪个接口
        return spare_send_sms($mobile,$content,$spareNum);
    }

}

/**
 * @desc: 生成32位随机订单号
 * @Author: cheng
 * @update: 2016-11-25
 **/
function get_Ordernums(){
    $str = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return md5($str);
}

/**
 * @desc: 发送微信方法
 * @Author: delayhsiao
 * @desc 返回成功：{"status":0,"message":"\u53d1\u9001\u6210\u529f"}，失败时status是1
 * @update: 2016-11-29
 **/
function send_weixin($data) {
        $wxUrl = "http://wx.baimixu.cn/msg2.php";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $wxUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $resJson = curl_exec($ch);
        curl_close($ch);
        return $resJson;
}
function send_weixin_bak($data){
//	wx2.baimixu.cn/msg2.php?mobile=15298370251&name=荀彧&mailno=31651511566&code=225654&company=申通快递&address=东山路&qtime=早上9点&remark=感谢您的使用&tel=02584185858
	foreach($data as $k => $v){
		$param[] = $k.'='.$v;
	}
	$wxUrl = "http://wx.baimixu.cn/msg2.php?".implode('&',$param);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $wxUrl);        //设置url
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);   //设置开启重定向支持
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	$output = curl_exec($ch);  //执行
	curl_close($ch);
	return $output;
}


/**
 * use_CURL()
 * 使用CURL
 * @param mixed $url            URL
 * @param bool $post            是否POST方式
 * @param mixed $post_param     如果是POST, 则参数
 * @return
 */
function use_CURL( $url, $post = FALSE, $post_param = Array(), $TimeOUT = 45 )
{
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_ENCODING, "");
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);

    if( $post === TRUE )
    {
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_param);
    }
    else
    {
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
    }


    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $TimeOUT);
    curl_setopt($curl, CURLOPT_TIMEOUT, $TimeOUT);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $data['content'] = curl_exec($curl);
    $data['error'] = curl_error($curl);
    $data['info'] = curl_getinfo($curl);

    curl_close($curl);

    return $data;
}

/**
 * @desc 韵达Url
 * @author quyang
 * @update 2017-1-3
 */
function send_yunda($url, $data){
    foreach($data as $k => $v){
        $param[] = $k.'='.$v;
    }
    $smsUrl = $url.'?'.implode('&',$param);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $smsUrl);        //设置url
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);   //设置开启重定向支持
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    $output = curl_exec($ch);  //执行
    curl_close($ch);
    return $output;
}

/**
 * Function DataType_Uniform
 * @param $_UniformDATA
 * @return array|string
 *
 * Author: 黄盖
 * Date: 2017-2-5 15:25
 * Info: 其他语言对数据类型比较严谨, 统一将类型转为string
 */
function DataType_Uniform( $_UniformDATA )
{
    if( is_array( $_UniformDATA ) )
    {
        foreach( $_UniformDATA as $key => $value )
        {
            $_UniformDATA[ $key ] = DataType_Uniform( $value );
        }

        return $_UniformDATA;
    }
    else
    {
        return strval( $_UniformDATA );
    }
}

/**
 * Desc:数组转XML
 * User:youtanzhi
 * Date:2017-02-13 13:21:30
 */
function arrayToXml($arr){
    $xml = "<request>";
    foreach ($arr as $key => $val) {
        if (is_array($val)) {
            $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
        } else{
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        }
    }
    $xml .= "</request>";
    return $xml;
}

/**
 * 根据站点id和包裹id查询是否使用包裹编号作为提货码
 * @auth farmer
 */
function get_special_pkg($station_id,$pkg_id,$tablename){
	$is_special = M('TpUser')->where('f_user_id = '.$station_id)->getField('f_professional');	//根据站点ID查看是否是专业站点
	if($is_special == 1){
		$package_num = M($tablename)->where('f_parcel_id = '.$pkg_id)->getField('f_num');
		if($package_num > 0){
			return $package_num;
		}
	}
	return false;
}


/**
 * [cUrl cURL(支持HTTP/HTTPS，GET/POST)]
 * @author farmer
 * @param     [string]     $url    [请求地址]
 * @param     [Array]      $header [HTTP Request headers array('Content-Type'=>'application/x-www-form-urlencoded')]
 * @param     [Array]      $data   [参数数据 array('name'=>'value')]
 * @return    [type]               [如果服务器返回xml则返回xml，不然则返回json]
 */
function myUrl($url,$header=null, $data = null){
	//初始化curl
	$curl = curl_init();
	//设置cURL传输选项
	if(is_array($header)){
		curl_setopt($curl, CURLOPT_HTTPHEADER  , $header);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

	if (!empty($data)){//post方式
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}

	//获取采集结果
	$output = curl_exec($curl);
	//关闭cURL链接
	curl_close($curl);
	//解析json
	$json=json_decode($output,true);
	//判断json还是xml
	if ($json) {
		return $json;
	}else{
		#验证xml
		libxml_disable_entity_loader(true);
		#解析xml
		$xml = simplexml_load_string($output, 'SimpleXMLElement', LIBXML_NOCDATA);
		return $xml;
	}
}

/**
 * 备用多接口发送，根据$spareNum 来决定接口 （三到四个备用接口）
 * @param unknown $mobile
 * @param unknown $content
 * @param unknown $sparetype
 */
function spare_send_sms($mobile,$content,$spareNum=1){
    
    switch ($spareNum){
        case 1:
            $res = chuanglan_send_sms($mobile,$content);        // 根据失败次数来决定不同的接口，失败一次调用创蓝接口重发
            break;
        case 2:
            // 其他接口 预留
            break;
        default:
            break;
    }
    return $res;
}

/**
 * 创蓝发送短信
 * @param unknown $mobile
 * @param unknown $content
 */
function chuanglan_send_sms($mobile,$content){
    Vendor('Sms.Chuanglan');
    $cSms= new \Chuanglan(C('CL_SMS.api_account'),C('CL_SMS.api_password'));
    return $cSms->sendSMS($mobile, $content);
    
}

/**
 * 多个短信平台转换一致的返回状态信息
 * @param unknown $data
 */
function tranSmsStatus($data){
    if($data['status'] == 'DTBLACK') 
        $data['status'] = 'MBBLACK';
    
    return $data;
}